package com.adapters.db;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.net.Uri;

import com.objects.Contact;
import com.objects.CountrySMSCode;
import com.objects.Group;

public class GroupTableAdapter {
	public static final String TABLE_NAME = ContentProviderDB.PREFIX + "groups";
	public static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS "
			+ TABLE_NAME + " (" + ContentProviderDB.COL_ID
			+ " integer primary key, " + ContentProviderDB.COL_TITLE
			+ " text, " + ContentProviderDB.COL_ORDER + " integer not null)";

	private Context mContext;

	public GroupTableAdapter(Context context) {
		mContext = context;
	}

	public void add(Group item, int order) {
		Uri contentUri = Uri.withAppendedPath(ContentProviderDB.CONTENT_URI,
				TABLE_NAME);
		ContentValues values = new ContentValues();
		values.put(ContentProviderDB.COL_ID, item.getID());
		values.put(ContentProviderDB.COL_TITLE, item.getTitle());
		values.put(ContentProviderDB.COL_ORDER, order);
		mContext.getContentResolver().insert(contentUri, values);

	}

	public boolean clear() {
		Uri contentUri = Uri.withAppendedPath(ContentProviderDB.CONTENT_URI,
				TABLE_NAME);
		int value = mContext.getContentResolver()
				.delete(contentUri, null, null);
		return value > 0;

	}

	public ArrayList<Group> getItems(String sortOrder) throws SQLException {
		ArrayList<Group> results = new ArrayList<Group>();
		Uri contentUri = Uri.withAppendedPath(ContentProviderDB.CONTENT_URI,
				TABLE_NAME);
		Cursor mCursor = null;
		if (sortOrder == null) {
			mCursor = mContext.getContentResolver().query(contentUri, null,
					null, null, ContentProviderDB.COL_ORDER + " ASC");
		} else {
			mCursor = mContext.getContentResolver().query(contentUri, null,
					null, null, sortOrder);
		}
		if (mCursor.moveToFirst()) {
			do {
				Group object = new Group();
				object.setTitle(mCursor.getString(mCursor
						.getColumnIndex(ContentProviderDB.COL_TITLE)));
				object.setID(mCursor.getLong(mCursor
						.getColumnIndex(ContentProviderDB.COL_ID)));
				results.add(object);
			} while (mCursor.moveToNext());
		}
		mCursor.close();
		return results;
	}

}
